﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.Practices.Unity;
using QLDV.Controllers;
using QLDV.Infrastructure.Config;
using QLDV.Infrastructure.IoC;
using QLDV.Models;

namespace QLDV
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : HttpApplication, IContainerProvider
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Account", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            InitializeIoC();
            AreaRegistration.RegisterAllAreas();
            
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        private static void InitializeIoC()
        {
            UnityContainer = new UnityContainer();
            UnityContainer
                // BlogSharpEntities has multiple contructors, need to tell Unity which one to invoke
                .RegisterType<QLDVEntities>(new PerRequestLifetimeManager(), new InjectionConstructor())
                .RegisterType<IQLDVRepository, QLDVRepository>(new TransientLifetimeManager())
                .RegisterType<IController, HomeController>("Home", new TransientLifetimeManager())
                .RegisterType<IController, AccountController>("Account", new TransientLifetimeManager())
                .RegisterType<IController, DoanVienController>("DoanVien", new TransientLifetimeManager())
<<<<<<< .mine
                .RegisterType<IController, LoaiCSDController>("loaiCSD", new TransientLifetimeManager())
                .RegisterType<IController, LoaiCSDController>("LoaiCSD", new TransientLifetimeManager())
                .RegisterType<IController, LoaiCSDController>("loaicsd", new TransientLifetimeManager())
                .RegisterType<IController, CsdController>("csd", new TransientLifetimeManager())
                .RegisterType<IController, ErrorController>("Error", new TransientLifetimeManager());
=======
                .RegisterType<IController, CSDController>("CSD", new TransientLifetimeManager())
                .RegisterType<IController, LoaiCSDController>("LoaiCSD", new TransientLifetimeManager());
>>>>>>> .r27
            ControllerBuilder.Current.SetControllerFactory(typeof(UnityControllerFactory));
        }

        private static IUnityContainer UnityContainer;

        public IUnityContainer Container
        {
            get { return UnityContainer; }
        }

        protected void Application_AuthenticateRequest()
        {
            if (IgnoreAuthenticateRequest())
                return;
            EnhancedPrincipal user;
            if (User != null &&
                User.Identity.IsAuthenticated &&
                User.Identity.AuthenticationType == "Forms")
            {
                var repository = (IQLDVRepository)Container.Resolve(typeof(IQLDVRepository));
                var dbUser = repository.FindAccountID(User.Identity.Name);
                user = new EnhancedPrincipal(User.Identity, dbUser);
            }
            else
            {
                user = EnhancedPrincipal.Anonymous;
            }
            HttpContext.Current.User = Thread.CurrentPrincipal = user;
        }

        private static readonly string[] IgnoredExtensions = new[]
                                                                 {
                                                                     ".js", ".css", ".txt", ".html", ".htm",
                                                                     ".xml", ".png", ".gif", ".jpg", ".ico"
                                                                 };

        private static bool IgnoreAuthenticateRequest()
        {
            var url = HttpContext.Current.Request.Url.AbsolutePath.ToLowerInvariant();
            return IgnoredExtensions.Any(url.EndsWith);
        }
    }
}